package com.qs.handler;

import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.qs.service.UserService;
import lombok.AllArgsConstructor;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * MyBatis Plus 自动填充
 */
@Component
@AllArgsConstructor
public class MyMetaObjectHandler implements MetaObjectHandler {
    private final DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    @Override
    public void insertFill(MetaObject metaObject) {
        if (metaObject.hasSetter("createUser") && metaObject.getValue("createUser") == null) {
            setFieldValByName("createUser", StpUtil.getLoginId(), metaObject);
        }
        setFieldValByName("createTime", LocalDateTime.now().format(dateTimeFormatter), metaObject);
        setFieldValByName("updateTime", LocalDateTime.now().format(dateTimeFormatter), metaObject);
        setFieldValByName("updateUser", StpUtil.getLoginId(), metaObject);
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        setFieldValByName("updateTime", LocalDateTime.now().format(dateTimeFormatter), metaObject);
        setFieldValByName("updateUser", StpUtil.getLoginId(), metaObject);
    }
}
